﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace RESP_IIWaterAssessment
{
    public partial class DrainagesForm : Form
    {
        public DrainagesForm()
        {
            InitializeComponent();
        }

        int regID, avpID, drID;
        bool insert = false, view = false;


        tb_drainage drainage;
        tb_drainageState drState;
        TextBox newDrainage = new TextBox();

        private void DrainagesForm_Load(object sender, EventArgs e)
        {
            cbAVP.Enabled = cbDrainage.Enabled = false;

            if (InformationClass.isAdmin)
            {
                cbRegion.SelectedIndexChanged -= cbRegion_SelectedIndexChanged;
                cbRegion.DataSource = UtilClass.FillCBRegions();
                cbRegion.DisplayMember = "Name";
                cbRegion.ValueMember = "ID";
                cbRegion.SelectedIndex = -1;
                cbRegion.Text = string.Empty;
                cbRegion.SelectedIndexChanged += new EventHandler(cbRegion_SelectedIndexChanged);
            }
            else
            {
                regID = InformationClass.regionID;
                cbRegion.Enabled = false;
                cbAVP.Enabled = true;
                cbAVP.DataSource = UtilClass.FillAVP(regID);
                cbAVP.DisplayMember = "Name";
                cbAVP.ValueMember = "ID";
                cbAVP.SelectedIndex = -1;
                cbAVP.Text = string.Empty;
            }
        }

        private void cbRegion_SelectedIndexChanged(object sender, EventArgs e)
        {
            cbAVP.SelectedIndexChanged -= cbAVP_SelectedIndexChanged;
            regID = Convert.ToInt32(cbRegion.SelectedValue);
            cbAVP.DataSource = UtilClass.FillAVP(regID);
            cbAVP.DisplayMember = "Name";
            cbAVP.ValueMember = "ID";
            cbAVP.SelectedIndex = -1;
            cbAVP.Text = string.Empty;
            cbAVP.Enabled = true;
            avpID = 0;
            cbAVP.SelectedIndexChanged += new EventHandler(cbAVP_SelectedIndexChanged);
        }

        private void cbAVP_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbAVP.SelectedIndex >= 0)
            {
                FillDrainage();
            }
            else
            {
                avpID = 0;
            }
        }

        private void FillDrainage()
        {
            cbDrainage.SelectedIndexChanged -= cbDrainage_SelectedIndexChanged;
            avpID = Convert.ToInt32(cbAVP.SelectedValue);
            cbDrainage.DataSource = DBClass.Drainages.Where(wh => wh.AVPID == avpID).Select(se => new
            {
                ID = se.ID,
                Name = se.Name
            })
            .OrderBy(o => o.Name)
            .ToArray();

            cbDrainage.DisplayMember = "Name";
            cbDrainage.ValueMember = "ID";
            cbDrainage.Enabled = true;
            cbDrainage.SelectedIndex = -1;
            cbDrainage.Text = string.Empty;
            cbDrainage.SelectedIndexChanged += new EventHandler(cbDrainage_SelectedIndexChanged);
        }

        private void cbDrainage_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cbDrainage.SelectedIndex >= 0)
            {
                drID = Convert.ToInt32(cbDrainage.SelectedValue);
                drainage = DBClass.Drainages.Where(wh => wh.ID == drID).SingleOrDefault();
                tbArea.Text = drainage.Area.GetValueOrDefault().ToString();
                tbCloseLength.Text = drainage.CloseLength.GetValueOrDefault().ToString();
                tbNote.Text = drainage.Note;
                tbOpenLength.Text = drainage.OpenLength.GetValueOrDefault().ToString();
            }
            else
            {
                drID = 0;
                drainage = null;
                tbArea.Text = tbCloseLength.Text = tbNote.Text = tbOpenLength.Text = string.Empty;
            }
        }

        private void buttonAdd_Click(object sender, EventArgs e)
        {
            if (InformationClass.Lang)
            {
                buttonOK.Text = "Создать";
                buttonCancel.Text = "Отмена";
            }
            else
            {
                buttonOK.Text = "Яратиш";
                buttonCancel.Text = "Бекор қилиш";
            }

            insert = true;

            cbDrainage.Visible = false;

            tbArea.Text = tbCloseLength.Text = tbNote.Text = tbOpenLength.Text = string.Empty;

            newDrainage = new TextBox();
            newDrainage.Location = cbDrainage.Location;
            newDrainage.Size = cbDrainage.Size;
            newDrainage.Text = string.Empty;
            tabDrainage.Controls.Add(newDrainage);

        }

        private void buttonCancel_Click(object sender, EventArgs e)
        {
            if (insert)
            {
                insert = false;
                newDrainage.Dispose();
                cbDrainage.Visible = true;
            }
            else
            {
                this.Close();
            }
        }

        private void buttonOK_Click(object sender, EventArgs e)
        {
            decimal area, OpLen, ClLen;

            tbArea.Text.GetDecimalOrDefault(out area);
            tbCloseLength.Text.GetDecimalOrDefault(out ClLen);
            tbOpenLength.Text.GetDecimalOrDefault(out OpLen);

            if (insert)
            {
                if (String.IsNullOrEmpty(newDrainage.Text) || avpID < 1)
                {
                    if (InformationClass.Lang)
                        MessageBox.Show("Не выбрано АВП или не заполнено название Дренажной системы");
                    else
                        MessageBox.Show("СИУ танланмаган ёки Дренаж тизими номи тўлдирилмаган");
                    return;
                }
                if (DBClass.Drainages.Where(wh => wh.AVPID == avpID && wh.Name == newDrainage.Text).Select(se => se.Name).ToArray().Contains(newDrainage.Text))
                {
                    MessageBox.Show(msgClass.msgUncorrectData);
                    newDrainage.Focus();
                    newDrainage.SelectAll();
                    return;
                }

                drainage = new tb_drainage
                {
                    AVPID = avpID,
                    Area = area,
                    Name = newDrainage.Text,
                    CloseLength = ClLen,
                    OpenLength = OpLen,
                    Note = tbNote.Text
                };
                DBClass.Drainages.InsertOnSubmit(drainage);
                DBClass.RESPContext.SubmitChanges();

                drState = new tb_drainageState
                {
                    DrainageID = drainage.ID,
                    Year = DateTime.Now.Year

                };
                DBClass.DrainagesState.InsertOnSubmit(drState);

                insert = false;
                cbDrainage.Visible = true;
                //FillDrainage();
                buttonOK.Text = "OK";
                buttonCancel.Text = "Cancel";

            }
            else
            {
                if (drainage != null)
                {
                    drainage.Area = area;
                    drainage.CloseLength = ClLen;
                    drainage.OpenLength = OpLen;
                    drainage.Note = tbNote.Text;
                }
            }
            try
            {
                if (DBClass.RESPContext.GetChangeSet().Deletes.Count > 0 || DBClass.RESPContext.GetChangeSet().Inserts.Count > 0 || DBClass.RESPContext.GetChangeSet().Updates.Count > 0)
                {
                    DBClass.RESPContext.SubmitChanges();
                    MessageBox.Show(msgClass.msgSubmitChanges, msgClass.msgAchtung);
                }
            }
            catch
            {
                if (insert)
                {
                    DBClass.Drainages.DeleteOnSubmit(drainage);
                    DBClass.RESPContext.SubmitChanges();
                }
                MessageBox.Show(msgClass.msgError, msgClass.msgAchtung);
            }
            FillDrainage();
            newDrainage.Dispose();
            cbDrainage.Visible = true;
            if (drainage != null)
                cbDrainage.SelectedValue = drainage.ID;
            buttonOK.Text = "OK";
            buttonCancel.Text = "Cancel";


        }

        private void tabControl1_TabIndexChanged(object sender, EventArgs e)
        {
            if (insert)
            {
                tabControl1.SelectedTab = tabDrainage;
                return;
            }

            if (tabControl1.SelectedTab == tabDrainage)
            {
                view = false;
            }
            else
                view = true;

            buttonShow.Visible = view;
        }

        private void buttonShow_Click(object sender, EventArgs e)
        {
            ShowDrainages();
        }

        private void ShowDrainages()
        {
            if (regID > 0 && avpID == 0)
            {
                dgvDrainages.DataSource = DBClass.Drainages
                    .Where(wh => UtilClass.GetAll_AVPID_in_regions(regID).Contains(wh.AVPID))
                    .Select(se => new
                    {
                        ID = se.ID,
                        DrName = se.Name,
                        Area = se.Area,
                        OpenLength = se.OpenLength,
                        Closelength = se.CloseLength
                    }).ToList();
            }
            else if (avpID > 0)
            {
                dgvDrainages.DataSource = DBClass.Drainages
                    .Where(wh => wh.AVPID == avpID)
                    .Select(se => new
                    {
                        ID = se.ID,
                        DrName = se.Name,
                        Area = se.Area,
                        OpenLength = se.OpenLength,
                        Closelength = se.CloseLength
                    }).ToList();
            }

            if (dgvDrainages.DataSource != null)
            {
                dgvDrainages.Columns["ID"].Visible = false;
                if (InformationClass.Lang)
                {
                    dgvDrainages.Columns["DrName"].HeaderText = "Название";
                    dgvDrainages.Columns["Area"].HeaderText = "Площадь (га)";
                    dgvDrainages.Columns["OpenLength"].HeaderText = "Открытая протяженность (км)";
                    dgvDrainages.Columns["Closelength"].HeaderText = "Закрытая протяженность (км)";
                }
                else
                {
                    dgvDrainages.Columns["DrName"].HeaderText = "Номи";
                    dgvDrainages.Columns["Area"].HeaderText = "Майдон (га)";
                    dgvDrainages.Columns["OpenLength"].HeaderText = "Очиқ масофа (км)";
                    dgvDrainages.Columns["Closelength"].HeaderText = "Ёпиқ масофаь (км)";
                }
                dgvDrainages.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.Fill;
                dgvDrainages.AutoResizeColumns();
            }
        }

        private void tsbDelete_Click(object sender, EventArgs e)
        {
            if (dgvDrainages.RowCount > 0 && dgvDrainages.CurrentRow != null)
            {
                drainage = DBClass.Drainages.Where(wh => wh.ID == (int)dgvDrainages["ID", dgvDrainages.CurrentRow.Index].Value).SingleOrDefault();
                if (drainage != null)
                {
                    if (MessageBox.Show(msgClass.msgDeleteQuestion, msgClass.msgAchtung, MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        DBClass.Drainages.DeleteOnSubmit(drainage);
                        DBClass.RESPContext.SubmitChanges();
                        FillDrainage();
                        ShowDrainages();
                    }
                }
            }
        }
    }
}
